package com.example.cloud.consume.order.loadbalanced;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义负载均衡算法实现类
 *
 * @author Frank
 * @create 2020-11-30 11:02
 **/
@Slf4j
@Component
public class MyLoadBalanced implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }

    /**
     * 获取下一个要调用的微服务的id
     * @return
     */
    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.weakCompareAndSet(current, next));
        log.info("*****next: " + next);
        return next;
    }

}
